<template>
  <DeviceCardEdit v-else v-model="editDevice" ref="deviceEdit">
    <template #footer>
      <div class="device-card-footer">
        <el-button type="primary" circle icon="el-icon-check" :loading="saving" @click="handleSave()">
        </el-button>
        <div>
          <el-button v-if="!saving" type="text" circle icon="el-icon-refresh-left" @click="handleReset()">
          </el-button>
          <el-button type="danger" circle icon="el-icon-close" @click="handleCancelEdit()" :loading="saving">
          </el-button>
        </div>

      </div>
    </template>
  </DeviceCardEdit>
</template>

<script>
import DeviceCardEdit from "@/components/new/device-card/DeviceCardEdit";
export default {
  name: "EditDeviceCard",
  components: {DeviceCardEdit},
  props: {
    initDevice: {
      default() {
        return {
          id: -1,
          name: '',
          os: '',
          ram: 1,
          processorArchitecture: ''
        }
      }
    },
    saveEdit: {
      default: undefined
    }
  },
  data(){
    return{
      editDevice: {...this.initDevice},
      saving: false
    }
  },
  methods: {
    handleReset(){
      this.editDevice = {...this.initDevice};
    },
    handleSave(){
      this.$refs['deviceEdit'].validate(valid => {
        if(valid){
          this.startSaving();
        }
      })
    },
    startSaving(){
      if(this.saveEdit){
        this.saving = true;
        this.saveEdit(this.editDevice)
            .then(res => {
              if(res.code === 200){
                this.editDevice = {...res.data}
                this.$emit('saved', {...res.data})
              }else{
                throw new Error(res.msg);
              }
            })
            .catch(err => {
              this.$emit('error', err);
            })
            .finally(() => {
              this.saving = false;
            });
      }
    },
    handleCancelEdit(){
      this.$emit('cancel');
    },
  }
}
</script>

<style scoped>
.device-card-footer{
  display: flex;
  justify-content: space-between;
}
</style>
